package com.gz.ezexcel.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.fastjson.JSON;
import com.gz.ezexcel.filter.FreezeAndFilter;
import com.gz.ezexcel.service.DownloadExcelService;
import com.gz.ezexcel.vo.ExcelVO;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * @author juice-gz
 * date 2022-01-06
 */
@Service
public class DownloadExcelServiceImpl implements DownloadExcelService {


    @Override
    public void downloadForFilter(HttpServletResponse response, List<ExcelVO> excelVOList) throws IOException {
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), ExcelVO.class)
                    .autoCloseStream(Boolean.FALSE)
                    .sheet("模板")
                    .registerWriteHandler(new FreezeAndFilter(0,0,2)) //参数 0第一行 0第一列 2第三列
                    .doWrite(excelVOList);
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = MapUtils.newHashMap();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }
}
